<template>
	<scroll-view scroll-y class="scroll-view-content" type="list">
		<div class="productionOrderDetails" :style="{
        paddingBottom:
          orderDetails?.DocumentStatus == 'C'
            ? 20 + 'px'
            : utils.windowBottom + 80 + 'px',
      }">
			<!-- 基本信息 -->
			<div class="orderData">
				<div class="order_head">
					<div class="order_head_left">基本信息</div>
				</div>
				<template v-for="(item, index) in baseInfoList" :key="index">
					<div class="formItem" :class="item?.type == 5 ? '' : 'flexCenter'"
						:style="{ borderBottom: item.type == 5 ? '0' : '1px solid #ccc' }" v-if="item.isShow">
						<div style="white-space: nowrap">
							<span class="required" v-if="item.required">*</span>{{ item.title }}
						</div>

						<div v-if="item.type == 3" style="font-size: 32rpx; display: flex; align-items: center;">
							{{ item.value || '' }}
							<span v-if="item.title == '单据编号'"
								style="color: #dd3f5b; font-size: 24rpx">{{ '（' + utils.getOrderStatus(item?.status) + '）' }}</span>
						</div>
						<div style="color: #3975f6;text-align: right;" @click.stop="clickSelect(item)"
							v-if="item.type == 2">
							{{!isEdit? item.value: item.value && item.value != ' '? item.value: '选择'}}
						</div>
						<input :disabled="!isEdit" v-else-if="item.type == 1" class="value"
							:type="item.title == '实收数量' ? 'number' : 'text'" v-model="item.value"
							:placeholder="isEdit ? '请输入' : ''" style="text-align: right; color: #3975f6" />

						<textarea v-else-if="item.type == 5" style="padding: 20rpx;
                border: 1px solid #ccc;
                height: 200rpx;
                margin-top: 20rpx;
				width: 100%;
				box-sizing: border-box;
              " :disabled="!isEdit" v-model="item.value" placeholder="请输入"
							placeholder-style="font-weight: 400; color: #999;" />
					</div>
				</template>
			</div>
			<!-- tab -->
			<div class="orderData">

				<div class="order_head">
					<div class="order_head_left">明细</div>
					<!-- <van-icon name="scan" @click="scan" /> -->
					<div>
						<van-button :disabled="!isEdit" type="primary" size="small" style="margin-right: 10rpx;"
							@click="add('手动')">手动</van-button>
						<van-button :disabled="!isEdit" type="primary" size="small" plain
							@click="add('扫码')">扫码</van-button>
					</div>
				</div>
				<!-- 明细信息 -->
				<template v-if="detailedList && detailedList.length > 0">
					<div style="padding: 20rpx; background: #f6f6f6;margin-bottom: 20rpx;"
						v-for="(detailedItem, detailedIndex) in detailedList" :key="detailedIndex">
						<template v-for="(item, index) in detailedItem" :key="index">

							<div class="formItem" :class="item?.type == 5 || item?.type == 6 ? '' : 'flexCenter'"
								:style="{ borderBottom: item.type == 5 ? '0' : '1px solid #ccc' }" v-if="item.isShow">
								<div
									style="display: flex;align-items: center;justify-content: space-between;white-space: nowrap">
									<div style="color:#666">{{ item.title }}</div>
								</div>
								<div style="font-size: 32rpx; display: flex; align-items: center;margin-left: 20rpx;text-align: right;"
									v-if="item.type == 3">
									{{ item.value }}
								</div>
								<div style="color: #3975f6;text-align: right;"
									@click.stop="clickSelect(item,detailedIndex)" v-else-if="item.type == 2">
									{{!isEdit? item.value: item.value && item.value != ' '? item.value: '选择'}}
								</div>
								<input :disabled="!isEdit" v-else-if="item.type == 1" class="value" :type="'text'"
									v-model="item.value" :placeholder="isEdit ? '请输入' : ''"
									style="text-align: right; color: #3975f6" />

								<checkbox v-else-if="item.type == 4" :checked="item.value" :disabled="!isEdit"
									@click.stop="item.value = !item.value" />

								<textarea v-else-if="item.type == 5" style="
					    padding: 20rpx;
					    border: 1px solid #ccc;
					    height: 200rpx;
					    width: 100%;
					    margin-top: 20rpx;
					    box-sizing: border-box;
					  " :disabled="!isEdit" v-model="item.value" placeholder="请输入"
									placeholder-style="font-weight: 400; color: #999;"></textarea>
								<!-- 附件上传 -->
								<div v-else-if="item.type == 6" style="
					    padding: 20rpx;
					    width: 300rpx;
					    position: relative;
					    box-sizing: border-box;
					  ">
									<div style="width: 260rpx; position: relative">
										<div style="
					        width: 100%;
					        height: 300rpx;
					        border: 1px solid #999;
					        border-radius: 10rpx;
					        display: flex;
					        align-items: center;
					        justify-content: center;
					      " v-if="!item.url" @click.stop="selectImage">
											<van-icon name="plus" size="40" color="#ccc" />
										</div>
										<image mode="widthFix" style="width: 100%; border: 1px solid #ccc"
											:src="item?.url" @click.stop="Utils.previewImageBase64(item?.url)" v-else>
										</image>
										<div style="
					        position: absolute;
					        top: -15rpx;
					        right: -25rpx;
					        z-index: 99;
					        border-radius: 50%;
					        background-color: #fff;
					      " @click.stop="deleteImage(item, index)">
											<van-icon name="close" size="30" color="red" v-if="item.url" />
										</div>
									</div>
								</div>
							</div>

						</template>
						<div class="flex" style="justify-content: flex-end;" v-if="isEdit">
							<van-button type="danger" size="small" :disabled="!isEdit"
								@click.stop="delDetails(detailedIndex)">删除</van-button>
						</div>
					</div>
				</template>

			</div>
		</div>
	</scroll-view>

	<template v-if="orderDetails?.DocumentStatus != 'C'">
		<orderBottomBtns :title="pageParams?.title" :FBillNo="orderDetails?.BillNo || ''"
			:DocumentStatus="orderDetails?.DocumentStatus || ''" @save-or-down="saveOrDown"
			@submit-order="submitOrderFn" @audit-order="auditOrderFn"></orderBottomBtns>
	</template>

	<template v-if="popType == '库存方向'">
		<van-action-sheet :show="isShowActionSheet" :actions="InventoryDirectionList" @select="selectFinishStatus"
			@close="close" />
	</template>
	<div style="padding-top: 20rpx" v-else-if="popType.includes('时间')">
		<van-action-sheet :show="isShowActionSheet" :title="!popType.includes('时间') ? actionSheetTitle : ''"
			@close="close">
			<van-datetime-picker type="datetime" :title="actionSheetTitle" :value="new Date().getTime()"
				:min-date="new Date().getTime()" :max-date="new Date(2099, 10, 1).getTime()" @confirm="confirmDateTime"
				@cancel="close" />
		</van-action-sheet>
	</div>
	<template v-else>
		<selectCom :pageTitle="pageParams?.title || ''" :FieldKeys="selectComFieldKeys" :isAddFUseOrgId="isAddFUseOrgId"
			:filterList="filterList" :FilterString="FilterString" :type="popType" :show="isShowActionSheet"
			@close="close" @submit="selectOrder">
		</selectCom>
	</template>
	<van-action-sheet :show="isShowSelectWarehouse" :actions="warehouseList" @close="isShowSelectWarehouse = false"
		@select="selectWarehouse" cancel-text="取消" />
	<selectDateTime :show="isShowDateTime" @close="isShowDateTime = false" @submit="selectDateTimeFn"></selectDateTime>
	<van-action-sheet :show="isShowSelectAssistantMethod" :actions="assistantList"
		@close="isShowSelectAssistantMethod = false" @select="selectAssistantMethod" cancel-text="取消" />
</template>

<script setup lang="ts">
	import utils from '@/utils';
	import selectCom from '@/components/selectCom.vue';
	import OrderBottomBtns from '@/components/orderBottomBtns.vue';
	import selectDateTime from '@/components/selectDateTime.vue';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { ref } from 'vue';
	import { getOrderDetailByBillNo, getOrderList, saveOrder, uploadFile01 } from '@/api/user';
	import { Utils } from '@/utils/utils';
	/**
	 * type 1 输入 2 选择 3 不能操作 4 开关 5 多行输入 6 图片上传
	 */
	const baseInfoList = ref({
		FBillNo: {
			title: '单据编号',
			value: '',
			status: '',
			type: 3,
			isShow: false,
		},
		FBillTypeID: {
			title: '单据类型',
			value: '直接调拨单',
			number: 'ZJDB01_SYS',
			type: '3',
			isShow: true,
		},
		FOwnerTypeOutIdHead: {
			title: '调出货主类型',
			value: '客户',
			number: 'BD_Customer',
			type: '3',
			isShow: false,
		},
		FOwnerTypeId: {
			title: '调入货主类型',
			value: '客户',
			number: 'BD_Customer',
			type: '3',
			isShow: false,
		},

		FStockOrgId: {
			title: '库存组织',
			formIdType: '组织机构',
			value: Utils.getStorage('currentOrganization')?.FName,
			number: Utils.getStorage('currentOrganization')?.FNumber,
			type: '2',
			isShow: true,
		},
		FDate: {
			title: '日期',
			value: Utils.formatDate(new Date().getTime()),
			number: '',
			type: '2',
			isShow: true,
			required: true,
		},
		FOwnerTypeIdHead: {
			title: '货主类型',
			value: 'BD_Customer',
			number: 'BD_Customer',
			type: '2',
			isShow: false,
		},
		FOwnerIdHead: {
			title: '货主',
			formIdType: '客户',
			value: '',
			number: '',
			type: '2',
			isShow: true,
			required: true,
		},
		FStockDirect: {
			title: '库存方向',
			value: 'GENERAL',
			number: '',
			type: '3',
			isShow: false,
		},


		FBaseCurrId: {
			title: ' 本位币',
			value: '',
			number: '',
			isShow: false,
		},

		F_Cycle: {
			title: '周期',
			value: '',
			number: '',
			type: '1',
			isShow: false,
		},

		// 备注
		FNOTE: { title: '备注', value: '', type: '5', isShow: true },
		// F_OtherStoreAttachment: { title: '附件', value: '', url: '', name: '', type: '6', isShow: false },
	});
	/** 明细列表*/
	const detailedList = ref([] as any)
	/** 明细内容项*/
	const detailedInfo = ref({
		FMaterialId: {
			title: '物料编码',
			formIdType: '物料',
			number: '',
			isShow: true,
			type: 3,
			actionSheetTitle: '请选择物料编码',
			require: true,
		},

		FMaterialName: {
			title: '物料名称',
			value: '',
			isShow: true,
			type: 3,
		},
		FSrcStockId: {
			title: '调出仓库',
			value: '',
			number: '',
			isShow: true,
			type: 3,
		},
		FSrcStockLocId: {
			title: '调出仓位',
			formIdType: '仓库',
			value: '',
			number: '',
			// 仓位集id
			id: '',
			isShow: true,
			type: 2,
		},
		FDestStockId: {
			title: '调入仓库',

			value: '',
			number: '',
			isShow: true,
			type: 3,
		},
		FDestStockLocId: {
			title: '调入仓位',
			formIdType: '仓库',
			value: '',
			number: '',
			// 仓位集id
			id: '',
			isShow: true,
			type: 2,
		},

		FOwnerTypeId: {
			title: '调入货主类型',
			value: 'BD_Customer',
			isShow: false,
			type: 3,
		},
		FOwnerId: {
			title: '调入货主',
			value: '',
			isShow: false,
			type: 3,
		},
		FOwnerTypeOutId: {
			title: '调出货主类型',
			value: 'BD_Customer',
			isShow: false,
			type: 3,
		},
		FOwnerOutId: {
			title: '调出货主',
			value: '',
			isShow: false,
			type: 3,
		},
		FUnitID: {
			title: '单位',
			value: '',
			number: '',
			isShow: true,
			type: 3,
		},
		FBaseQty: {
			title: '调拨数量',
			value: '',
			isShow: true,
			type: 1,
		},
		FKEEPERTYPEID: {
			title: '保管者类型',
			value: '',
			number: '',
			isShow: false,
			type: 2,
		},
		FKEEPERID: {
			title: '保管者',
			value: '',
			number: '',
			isShow: false,
			type: 2,
		},
		FLot: {
			title: '批号',
			formIdType: '即时库存',
			value: '',
			number: '',
			isShow: true,
			type: 2,
		},
		FProduceDate: {
			title: '生产日期',
			value: '',
			number: '',
			isShow: true,
			type: 3,
		},
		FExpiryDate: {
			title: '有效期至',
			value: '',
			number: '',
			isShow: true,
			type: 3,
		},



	});
	// 删除明细列表
	const delDetails = (index : number) => {
		Utils.showModal('是否删除该物料吗？', () => {
			detailedList.value.splice(index, 1)
		});
	}



	// 是否显示仓库选择
	const isShowSelectWarehouse = ref(false)
	// 仓库列表
	const warehouseList = ref()
	// 选择仓库
	const selectWarehouse = (e : any) => {
		const value = e.detail
		utils.navigateTo(
			'order/submitOrder' +
			'/index?仓库编号=' + value['仓库编号'] +
			'&仓库名称=' +
			value['仓库名称'] +
			'&仓位名称=' +
			value['仓位名称'] +
			'&仓位编号=' +
			value['仓位编号'] +
			'&仓位集id=' +
			value['仓位集id'] +
			'&客户编码=' +
			baseInfoList.value.FOwnerIdHead.number +
			'&客户名称=' +
			baseInfoList.value.FOwnerIdHead.value +
			'&parentPage=调拨单'
		);
	}
	// 添加物料
	const add = (type : string) => {
		if (!isEdit.value) return Utils.showToast('单据已审核，不允许修改！')
		// 如果客户为空直接提示
		if (baseInfoList.value.FOwnerIdHead.number == '') {
			return Utils.showErr('请先选择货主')
		}
		if (type == '手动') {
			clickSelect({
				formIdType: '仓库',
			})
		} else {
			scan()
		}
	}
	/**
	 * 扫码获取仓库
	 */
	const scan = () => {
		Utils.scanCode(async (res : any, code : string) => {
			console.log(code);
			// 获取仓库信息
			if (code) {
				await getWarehouseInfo(code);
			} else {
				Utils.showErr('解析二维码数据失败，请联系管理员！')
			}



		})
	};

	/**
	 * 通过仓位值获取仓库信息
	 */
	const getWarehouseInfo = async (code : string = '') => {
		const res : any = await getOrderList({
			data: JSON.stringify({
				FormId: Utils.getFormId('仓库'),
				// 仓库，仓位值
				FieldKeys: 'FNumber,FName,FFlexEntryId.FNumber,FFlexEntryId.FName,FFlexId,FUseOrgId.FNumber',
				FilterString: [
					Utils.getFilterString('FFlexEntryId.FNumber', code, code ? '67' : 'Like', '', ''),
					Utils.getFilterString('FDocumentStatus', 'C', '105', '', ''),
					Utils.getFilterString('FForbidStatus', 'A', '105', '', ''),
					Utils.getFilterString('FUseOrgId.FNumber', Utils.getStorage('currentOrganization')?.FNumber, '67', '', '')
				],
				OrderString: '',
			}),
		})

		warehouseList.value = []
		if (res && res.length > 0) {

			if (res.length == 1) {
				utils.navigateTo(
					'order/submitOrder' +
					'/index?仓库名称=' + res[0][1] +
					'&仓库编号=' +
					res[0][0] +
					'&仓位名称=' +
					res[0][3] +
					'&仓位编号=' +
					code +
					'&仓位集id=' +
					res[0][4] +
					'&客户编码=' +
					baseInfoList.value.FOwnerIdHead.number +
					'&客户名称=' +
					baseInfoList.value.FOwnerIdHead.value +
					'&parentPage=调拨单'
				);
			} else {
				res.forEach((v : any) => {
					console.log(v);
					warehouseList.value.push({
						name: v[1],
						仓库名称: v[1],
						仓库编号: v[0],
						仓位编号: v[2],
						仓位名称: v[3],
						仓位集id: v[4]

					})
				});
				isShowSelectWarehouse.value = true;
			}

		} else {
			Utils.showErr('找不到对应的仓库，请联系管理员！')
		}
	}


	// 选择图片
	const selectImage = async (event : any) => {
		Utils.selectFile((res : any) => {
			// repairMoldInfoList.value.F_WALA_ModelRepairImage.url =
			// 	res.tempFiles[0].tempFilePath;
			// repairMoldInfoList.value.F_WALA_ModelRepairImage.name =
			// 	Utils.generateUniqueString() +
			// 	'.' +
			// 	Utils.getLastElement(res.tempFiles[0].tempFilePath);
		});
	};
	/**
	 * 删除图片
	 */
	const deleteImage = (item : any, index : any) => {
		Utils.showModal('确定删除该图片吗', () => {
			// repairMoldInfoList.value[index].value = '';
			// repairMoldInfoList.value[index].url = '';
			// repairMoldInfoList.value[index].name = '';
		});
	};
	/**
	 * 获取base64
	 */
	function fileToBase64(filePath : string) {
		return new Promise((resolve, reject) => {
			// 读取文件内容
			uni.getFileSystemManager().readFile({
				filePath,
				encoding: 'base64',
				success: (res) => {
					resolve(res.data);
				},
				fail: (err) => {
					console.error('文件读取失败:', err);
					reject(err);
				},
			});
		});
	}

	/**
	 * 完成状态
	 */
	const InventoryDirectionList = ref([
		// { name: '修理中', value: 'A' },
		{ name: '普通', value: 'GENERAL' },
		{ name: '已报废', value: 'B' },
	]);
	const selectFinishStatus = (e : any) => {

	};
	// 显示时间选择弹窗
	const isShowDateTime = ref(false)
	// 选择时间
	const selectDateTimeFn = (e : any) => {
		if (popType.value == '日期') {
			baseInfoList.value.FDate.value = e;
			return;

		}


	}
	// 选择计费方式弹窗
	const isShowSelectAssistantMethod = ref(false)
	const assistantList = ref([] as any)
	const selectAssistantMethod = async (e) => {
		const value = e.detail
		if (popType.value == '计费标准') {
			// detailedList.value[currentClickIndex.value].F_VEFL_BillingStandard.value = value.FName;
			// detailedList.value[currentClickIndex.value].F_VEFL_BillingStandard.number = value.FNumber;
			return;
		}
		// detailedList.value[currentClickIndex.value].F_VEFL_CalculationMethod.value = value.FName;
		// detailedList.value[currentClickIndex.value].F_VEFL_CalculationMethod.number = value.FNumber;
	}

	// 显示选择弹窗
	const isShowActionSheet = ref(false);
	const actionSheetTitle = ref('请选择');
	// 查询字段
	const selectComFieldKeys = ref('')
	// 添加组织字段
	const isAddFUseOrgId = ref(true)
	// 弹窗过滤列表
	const filterList = ref([] as any)
	// 过滤字段集合
	const FilterString = ref([] as any)
	/**
	 * 是否编辑
	 */
	const isEdit = ref(false);
	/**
	 * 上传附件
	 */
	const uploadFileFn = async () => {
		// // 判断附件是否变化
		// if (
		// 	!orderDetails.value?.Id ||
		// 	!repairMoldInfoList.value.F_WALA_ModelRepairImage.url ||
		// 	repairMoldInfoList.value.F_WALA_ModelRepairImage.name ==
		// 	orderDataOrigin.value.F_WALA_ModelRepairImage.name
		// )
		// 	return;
		// // 更新附件信息
		// const base64 : any = await fileToBase64(
		// 	repairMoldInfoList.value.F_WALA_ModelRepairImage.url
		// );
		// const file : any = await uploadFile01({
		// 	data: JSON.stringify({
		// 		FileName: repairMoldInfoList.value.F_WALA_ModelRepairImage.name,
		// 		IsLast: true,
		// 		SendByte: base64,
		// 	}),
		// });
		// repairMoldInfoList.value.F_WALA_ModelRepairImage.value = file.Result.FileId;
		// console.log(
		// 	repairMoldInfoList.value.F_WALA_ModelRepairImage.value,
		// 	'附件变化了'
		// );
	};
	/**
	 * 保存
	 */
	const saveOrDown = async () => {
		await uploadFileFn();

		// 表单校验
		if (isEdit.value) {
			// 判断 replaceInfoList.value对象中的每一项是否有值
			let isOk = true,
				text = '';

			for (const key in baseInfoList.value) {
				if (Object.prototype.hasOwnProperty.call(baseInfoList.value, key)) {
					const element = baseInfoList.value[key];
					if (!element.value && element?.required) {
						// 如果值为空，则提示用户，并终止循环
						isOk = false;
						text = '请选择' + baseInfoList.value[key]?.title;
						break;
					}
				}
			}
			// for (const key in detailedInfo.value) {
			// 	if (Object.prototype.hasOwnProperty.call(detailedInfo.value, key)) {
			// 		const element = detailedInfo.value[key]?.value;
			// 		if (!element && detailedInfo.value[key]?.required) {
			// 			// 如果值为空，则提示用户，并终止循环
			// 			isOk = false;
			// 			text = '请选择' + detailedInfo.value[key]?.title;
			// 			break;
			// 		}
			// 	}
			// }

			// }
			if (!isOk) {
				return Utils.showErr(text);
			}
		}

		// 保存
		Utils.showModal('确定保存？', () => {
			saveOrderFn();
		});
	};

	/**
	 * 提交订单
	 */
	const submitOrderFn = async (res : Boolean) => {
		if (res) getOrderDetailsByBillNo(baseInfoList.value.FBillNo.value);
	};

	/**
	 * 审核单据
	 */
	const auditOrderFn = async (res : Boolean) => {
		if (res) getOrderDetailsByBillNo(baseInfoList.value.FBillNo.value);
	};

	/**
	 * 获取需要修改的字段
	 */
	const orderDataOrigin = ref();
	const detailedListOrigin = ref([] as any)
	const getNeedUpDateFields = () => {
		if (!orderDataOrigin.value) return [];
		const keys = Object.keys(baseInfoList.value);
		let needUpDateFields = keys.filter((key) => {
			return baseInfoList.value[key].value != orderDataOrigin?.value[key].value;
		});
		let needUpDateFields1 = Object.keys(detailedInfo.value)







		return [
			...new Set([
				...needUpDateFields,
				...needUpDateFields1,
				'FOWNERTYPEID'
			]),
		];
	};

	const saveOrderFn = async () => {
		const params : any = {};
		console.log(detailedList.value);
		if (pageParams?.value?.FBillNo) {
			const arr = getNeedUpDateFields();
			if (arr.length == 0) return Utils.showErr('数据没有改动，无需保存！');
			params.NeedUpDateFields = params.NeedReturnFields = arr;
		}
		console.log(params.NeedUpDateFields, 'NeedUpDateFields');


		const Model = {
			"FID": 0,
			"FBillNo": "",
			"FBillTypeID": {
				"FNUMBER": baseInfoList.value.FBillTypeID.number
			},
			"FStockOrgId": {
				"FNumber": baseInfoList.value.FStockOrgId.number
			},
			"FStockDirect": baseInfoList.value.FStockDirect.value,
			"FDate": baseInfoList.value.FDate.value,
			'FOwnerTypeOutIdHead': baseInfoList.value.FOwnerTypeOutIdHead.number,

			// "FDEPTID": {
			// 	"FNumber": baseInfoList.value.FDEPTID.number
			// },
			// "FACCEPTANCE": {
			// 	"FStaffNumber": baseInfoList.value.FACCEPTANCE.FStaffNumber
			// },
			"FSTOCKERID": {
				"FNumber": baseInfoList.value.FStockOrgId.number
			},
			// 库存组
			// "FSTOCKERGROUPID": {
			// 	"FNumber": baseInfoList.value.fstocker
			// },
			"FOwnerTypeIdHead": baseInfoList.value.FOwnerTypeIdHead.value,
			"FOwnerIdHead": {
				"FNumber": baseInfoList.value.FOwnerIdHead.number
			},
			// 客户
			"FCustId": {
				"FNumber": baseInfoList.value.FOwnerIdHead.number
			},
			"FNOTE": baseInfoList.value.FNOTE.value,


			"FBillEntry": [

			]
		};
		Model.FBillEntry = detailedList.value.map((item : any) => {
			return {
				"FEntryID": 0,

				"FMaterialId": {
					"FNumber": item.FMaterialId.number
				},
				"FUnitID": {
					"FNumber": item.FUnitID.number
				},
				"FBaseQty": item.FBaseQty.value,
				// 批号
				"FLot": {
					"FNumber": item.FLot.number
				},
				// 调入仓库
				"FDestStockId": {
					"FNumber": item.FDestStockId.number
				},
				// 调入仓位
				"FDestStockLocId": {
					["FDestStockLocId__FF" + item.FDestStockLocId.id]: {
						"FNumber": item.FDestStockLocId.number
					},
				},
				// 调出仓库
				"FSrcStockId": {
					"FNumber": item.FSrcStockId.number
				},
				// 调出仓位
				"FSrcStockLocId": {
					["FSrcStockLocId__FF" + item.FSrcStockLocId.id]: {
						"FNumber": item.FSrcStockLocId.number
					},
				},
				// 生产日期
				FProduceDate: item.FProduceDate.value,
				// 有效期至
				FExpiryDate: item.FExpiryDate.value,
				"FOWNERTYPEID": "BD_Customer",
				"FOWNERID": {
					"FNumber": baseInfoList.value.FOwnerIdHead.number
				},
				// 保管者类型
				"FKEEPERTYPEID": "BD_KeeperOrg",
				// 保管者
				"FKEEPERID": {
					"FNumber": baseInfoList.value.FStockOrgId.number
				},



			}
		});
		if (orderDetails.value?.Id) {
			Model.FID = orderDetails.value.Id;
		}
		params.Model = Model
		console.log(params);
		// return;

		const res : any = await saveOrder({
			FormId: Utils.getFormId('调拨单'),
			data: JSON.stringify(params),
		});
		console.log(res, '保存订单');
		if (res.Result.ResponseStatus.IsSuccess) {
			Utils.showErr('保存成功', () => {
				if (res.Result?.Number) {
					pageParams.value.FBillNo = res.Result?.Number;
					getOrderDetailsByBillNo(res.Result?.Number);
				}
			});
		} else {
			Utils.showErr(res.Result.ResponseStatus.Errors[0].Message);
		}
	};

	/**
	 * 获取搜索数据
	 */
	// 弹窗类型（获取不同的基础资料数据）
	const popType = ref('');
	// 选中项标题
	const poptitle = ref('')
	const popPlaceholder = ref('请输入');
	// 当前点击单据体index，-1为单据头
	const currentClickIndex = ref(-1)
	// 点击选择
	const clickSelect = async (item : any, index : number = -1) => {
		console.log(item, '---');

		if (!isEdit.value) return;
		selectComFieldKeys.value = ''
		FilterString.value = []
		filterList.value = []
		currentClickIndex.value = index;
		isAddFUseOrgId.value = true;
		popType.value = item.formIdType || item.title || '';
		poptitle.value = item.title;
		if (item.title == '计费方式' || item.title == '计费标准') {
			assistantList.value = await Utils.getAssistantInfo(item.title == '计费标准' ? '001' : 'RKDJFFS')
			isShowSelectAssistantMethod.value = true
			return
		}

		if (item.title == '日期') {
			isShowDateTime.value = true
			return
		}
		if (item.title == '验收员') {
			// 设置获取字段
			selectComFieldKeys.value = "FNumber,FName,FStaffNumber,FDocumentStatus,FForbidStatus,FUseOrgId.FNumber"
		} else if (item.title == '仓位') {
			// 设置获取字段
			selectComFieldKeys.value = "FNumber,FName,FFlexEntryId.FNumber,FFlexEntryId.FName,FFlexId,FDocumentStatus,FForbidStatus"
		} else if (item.title == '费用项目') {

			selectComFieldKeys.value = "FNumber,FName,FDocumentStatus,FForbidStatus"
			isAddFUseOrgId.value = false;
		} else if (item.title == '物料编码') {
			selectComFieldKeys.value = "FNumber,FName,FDocumentStatus,FForbidStatus,FUseOrgId.FNumber,F_BelongCustomer.FNumber"
			FilterString.value = [
				Utils.getFilterString('F_BelongCustomer.FNumber', baseInfoList.value.FOwnerIdHead.number, '=')
			]
		} else if (item.title == "库存组织") {
			selectComFieldKeys.value = "FNumber,FName,FForbidStatus,FDocumentStatus"
			isAddFUseOrgId.value = false
		} else if (item.title == '批号') {
			// selectComFieldKeys.value = "FNumber,FName,FCustId.FNumber,FMaterialId.FNumber,FForbidStatus,FDocumentStatus"
			// isAddFUseOrgId.value = false
			// filterList.value = [{ name: '编号', value: 1, key: 'FNumber' }]
			// FilterString.value = [
			// 	Utils.getFilterString('FCustId.FNumber', baseInfoList.value.FOwnerIdHead.number, '='),
			// 	Utils.getFilterString('FMaterialId.FNumber', detailedList.value[index].FMaterialId.number, '='),
			// ]
			selectComFieldKeys.value = "FLot.FNumber,FExpiryDate,FProduceDate,FBaseQty,FOwnerId.FNumber,FStockOrgId.FName"
			isAddFUseOrgId.value = false
			filterList.value = [{ name: '批号', value: 1, key: 'FLot.FNumber' }]
			FilterString.value = [
				Utils.getFilterString('FOwnerId.FNumber', baseInfoList.value.FOwnerIdHead.number, '='),
				Utils.getFilterString('FMaterialId.FNumber', detailedList.value[index].FMaterialId.number, '='),
				Utils.getFilterString('FStockOrgId.FNumber', Utils.getStorage('currentOrganization')?.FNumber, '='),
				Utils.getFilterString('FBaseQty', 0, '>'),
			]
		} else if (item.formIdType == '仓库') {
			// 设置过滤列表
			filterList.value = [
				{ name: '仓库名称', value: 0, key: "FName" },
				{ name: '仓库编号', value: 1, key: 'FNumber' },
				{ name: '仓位编号', value: 2, key: "FFlexEntryId.FNumber" },
			]
			// 设置获取字段
			selectComFieldKeys.value = "FNumber,FName,FFlexEntryId.FNumber,FFlexEntryId.FName,FFlexId,FDocumentStatus,FForbidStatus"
		}
		// 

		popPlaceholder.value = item.popPlaceholder || '请输入关键字搜索';
		actionSheetTitle.value = item?.actionSheetTitle || '请选择';
		setTimeout(() => {
			// console.log('进来了吗',selectComFieldKeys.value);
			isShowActionSheet.value = true;
		}, 10);
	};
	// 获取搜索数据
	const setValue = (data : any, value : any, number ?: string) => {
		const key = getKey(data, popType.value);
		if (key) {
			data[key].value = value;
			if (number) data[key].number = number;
		}
	};
	/**
	 * 选择时间
	 */
	const confirmDateTime = (e : any) => {
		setValue(detailedInfo.value, Utils.formatTimestamp(Number(e.detail)));
	};
	const close = () => {
		isShowActionSheet.value = false;
		popType.value = '';
	};
	// const setObj
	// 弹窗点击确定
	const selectOrder = async (value : any) => {
		

		// 设置单据体信息
		if (currentClickIndex.value != -1) {
			console.log(value, currentClickIndex.value, popType.value);
			const currentObj = detailedList.value[currentClickIndex.value]
			console.log(currentObj, 'currentObj');

			if (popType.value == '仓库') {

				// 设置仓位
				const d = JSON.parse(value.Value)
				console.log(poptitle.value, d);
				if (poptitle.value == '调入仓位') {
					// 设置仓库
					currentObj.FDestStockId.value = value.FName
					currentObj.FDestStockId.number = value.FNumber
					currentObj.FDestStockLocId.id = d[4]
					currentObj.FDestStockLocId.number = d[2]
					currentObj.FDestStockLocId.value = d[3]
				} else if (poptitle.value == '调出仓位') {
					currentObj.FSrcStockId.value = value.FName
					currentObj.FSrcStockId.number = value.FNumber
					currentObj.FSrcStockLocId.id = d[4]
					currentObj.FSrcStockLocId.number = d[2]
					currentObj.FSrcStockLocId.value = d[3]
				}


			}
			else if (popType.value == '即时库存') {

				currentObj.FLot.value = value.FNumber || '';
				currentObj.FLot.number = value.FNumber || '';
				const d = JSON.parse(value.Value)
				console.log(d, '---');
				// 生产日期
				currentObj.FProduceDate.value = d[1] ? Utils.formatDate(new Date(d[2]).getTime()) : ''
				// 有效期至
				currentObj.FExpiryDate.value = d[2] ? Utils.formatDate(new Date(d[1]).getTime()) : ''

			} else if (popType.value == '物料') {
				// 物料编号
				currentObj.FMaterialId.value = value.FNumber || ''
				currentObj.FMaterialId.number = value.FNumber || ''
				// 物料名称
				currentObj.FMaterialName.value = value.FName || ''

			}

			return;
		}

		// 设置单据头信息
		for (var key in baseInfoList.value) {
			if (baseInfoList.value.hasOwnProperty(key)) {
				var element = baseInfoList.value[key];

				if ((element.formIdType && element.formIdType == popType.value) || (element.title == popType.value)) {
					baseInfoList.value[key].value = value.FName
					baseInfoList.value[key].number = value.FNumber
					if (popType.value == '员工任岗') {
						baseInfoList.value[key].FStaffNumber = JSON.parse(value.Value)[2]
					}else if(popType.value == '组织机构'){
						 await Utils.selectData(value)
					}
				}
			}
		}
		// 手动选择仓库
		if (popType.value == '仓库') {
			const v = JSON.parse((value.Value))
			console.log(v, popType.value);
			utils.navigateTo(
				'order/submitOrder' +
				'/index?仓库名称=' + v[1] +
				'&仓库编号=' +
				v[0] +
				'&仓位名称=' +
				v[3] +
				'&仓位编号=' +
				v[2] +
				'&仓位集id=' +
				v[4] +
				'&客户编码=' +
				baseInfoList.value.FOwnerIdHead.number +
				'&客户名称=' +
				baseInfoList.value.FOwnerIdHead.value +
				'&parentPage=调拨单'

			);
		}

		close();
	};
	/**
	 * 通过对象的值获取对象的key
	 */
	const getKey = (obj : any, value : any) => {
		return Object.keys(obj).find((key) => obj[key].title == value);
	};



	/**
	 * 获取调拨单详情
	 */
	const orderDetails = ref({} as any);
	const getOrderDetailsByBillNo = async (Number : string) => {
		const res : any = await getOrderDetailByBillNo({
			FormId: Utils.getFormId('调拨单'),
			data: JSON.stringify({
				Number,
			}),
		});
		utils.setPageTitle(pageParams.value?.title + '详情');

		if (res.Result.ResponseStatus.IsSuccess) {
			const data = res.Result.Result;
			const {
				BillNo,
				BillTypeID,
				StockOrgId,
				StockDirect,
				OwnerTypeIdHead,
				OwnerIdHead,

				DocumentStatus,
				Note
			} = data;
			console.log(data, '调拨单详情');

			// 判断订单状态
			isEdit.value =
				data.DocumentStatus == 'B' || data.DocumentStatus == 'C' ? false : true;
			// 调拨单详情
			orderDetails.value = data;
			/** 设置单据头信息 */
			// 单据编号
			baseInfoList.value.FBillNo.value = BillNo;
			baseInfoList.value.FBillNo.isShow = true;
			baseInfoList.value.FBillNo.status = DocumentStatus
			// 单据类型
			baseInfoList.value.FBillTypeID.value = BillTypeID?.Name[0]?.Value
			baseInfoList.value.FBillTypeID.number = BillTypeID?.Number
			// 库存组织
			baseInfoList.value.FStockOrgId.value = StockOrgId?.Name[0]?.Value
			baseInfoList.value.FStockOrgId.number = StockOrgId?.Number
			// 日期
			if(data['Date']){
			
				baseInfoList.value.FDate.value = data['Date']  ? Utils.formatDate(new Date(data['Date'] ).getTime()) : ''
			}

			// 货主类型
			baseInfoList.value.FOwnerTypeIdHead.value = OwnerTypeIdHead || 'BD_Customer';
			// 货主
			baseInfoList.value.FOwnerIdHead.value = OwnerIdHead?.Name[0]?.Value || ''
			baseInfoList.value.FOwnerIdHead.number = OwnerIdHead?.Number || ''



			//  库存方向
			baseInfoList.value.FStockDirect.value = StockDirect || ''

			// 备注
			baseInfoList.value.FNOTE.value = Note
			// 设置单据体
			setFEntity()

			orderDataOrigin.value = JSON.parse(
				JSON.stringify({
					...baseInfoList.value,

				})
			);
		} else {
			Utils.showErr('调拨单详情获取失败');
		}
	};
	/**
	 * 设置单据体
	 */
	const setFEntity = () => {
		detailedList.value = []
		detailedListOrigin.value = []
		const FEntity = orderDetails.value.TransferDirectEntry;
		if (FEntity?.length > 0) {
			FEntity.forEach((v : any) => {
				const { MaterialId, StockId, SrcStockId, SrcStockLocId, DestStockId, DestStockLocId,
					UnitId, BaseQty, EntryNote, Lot, ProduceDate, ExpiryDate } = v;
				const obj = JSON.parse(JSON.stringify(detailedInfo.value))
				// 物料编号
				obj.FMaterialId.value = MaterialId?.Number || ''
				obj.FMaterialId.number = MaterialId?.Number || ''
				// 物料名称
				obj.FMaterialName.value = MaterialId?.Name[0]?.Value || ''
				// 调出仓库
				obj.FSrcStockId.value = SrcStockId?.Name[0]?.Value
				obj.FSrcStockId.number = SrcStockId?.Number
				// 调出仓位
				const stockOut = getStockPlace(SrcStockLocId);

				if (stockOut && stockOut.Number) {
					obj.FSrcStockLocId.value = stockOut?.Name[0]?.Value
					obj.FSrcStockLocId.number = stockOut?.Number
					obj.FSrcStockLocId.id = stockOut?.FFId
				}
				// 调入仓库
				obj.FDestStockId.value = DestStockId?.Name[0]?.Value
				obj.FDestStockId.number = DestStockId?.Number
				// 调入仓位
				const stockIn = getStockPlace(DestStockLocId);

				if (stockIn && stockIn.Number) {
					obj.FDestStockLocId.value = stockIn?.Name[0]?.Value
					obj.FDestStockLocId.number = stockIn?.Number
					obj.FDestStockLocId.id = stockIn?.FFId
				}

				//  单位
				obj.FUnitID.value = UnitId?.Name[0].Value || '';
				obj.FUnitID.number = UnitId?.Number || '';
				//  数量
				obj.FBaseQty.value = BaseQty || 0
				// 批号
				obj.FLot.value = Lot?.Number || ''
				obj.FLot.number = Lot?.Number || ''
				// 生产日期
				obj.FProduceDate.value = ProduceDate ? Utils.formatDate(new Date(ProduceDate).getTime()) : ''
				// 有效期至
				obj.FExpiryDate.value = ExpiryDate ? Utils.formatDate(new Date(ExpiryDate).getTime()) : ''



				detailedList.value.push(obj)
			});
		}
		console.log(detailedList.value, '----');
		detailedListOrigin.value = JSON.parse(JSON.stringify(detailedList.value))

	}
	/**
	 * 获取仓位信息 
	 */
	const getStockPlace = (obj : any) => {
		let stock : any = {}
		for (var key in obj) {
			if (obj.hasOwnProperty(key)) {
				var element = obj[key];
				// 找到有数据的对象（仓位）
				if (element) {
					if (element.Id) {
						stock = {
							...element,
							FFId: key.replace('F', '')
						};
					}

				}
			}
		}
		return stock;
	}
	/**
	 * 去掉值左右空格
	 */
	const trimFn = (str : string | number) => {
		if (!str && str != 0) return '';
		str = str + '';
		return str.replace(/(^\s*)|(\s*$)/g, '');
	};


	/** 页面参数 */
	const pageParams = ref();
	// 页面加载完成
	onLoad(async (opt : any) => {
		pageParams.value = opt;
		// 设置页面标题
		utils.setPageTitle(opt.FBillNo ? opt?.title + '详情' : '新增' + opt?.title);
		isEdit.value = opt.FBillNo ? false : true;
		if (opt.FBillNo) {
			getOrderDetailsByBillNo(opt.FBillNo);
		}

	});
	// 页面显示
	onShow(() => {
		const addMaterial = Utils.getStorage('addMaterial')
		console.log(addMaterial, 'addMaterial');
		Utils.removeStorage('addMaterial')
		if (addMaterial) {
			// 列表
			const list = addMaterial.list
			// 仓库信息
			const warehouse = addMaterial.warehouse
			list.forEach((v : any) => {
				const obj = JSON.parse(JSON.stringify(detailedInfo.value))
				// 物料编号
				obj.FMaterialId.value = v.FNumber?.value || ''
				obj.FMaterialId.number = v.FNumber?.value || ''
				// 物料名称
				obj.FMaterialName.value = v.FName?.value || ''
				// 调出仓库
				obj.FSrcStockId.value = warehouse.仓库名称
				obj.FSrcStockId.number = warehouse.仓库编号
				// 调出仓位
				obj.FSrcStockLocId.value = warehouse.仓位名称
				obj.FSrcStockLocId.number = warehouse.仓位编号
				obj.FSrcStockLocId.id = warehouse.仓位集id
				// 调入仓库
				obj.FDestStockId.value = v.FDestStockId.value
				obj.FDestStockId.number = v.FDestStockId.number
				// 调入仓位
				obj.FDestStockLocId.value = v.FDestStockLocId.value
				obj.FDestStockLocId.number = v.FDestStockLocId.number
				obj.FDestStockLocId.id = v.FDestStockLocId.id
				// 单位
				obj.FUnitID.value = v.Unit?.value || '';
				obj.FUnitID.number = v.Unit?.value || '';
				// 数量
				obj.FBaseQty.value = v.qty?.value || 0
				// 批号
				obj.FLot.value = v.FLot?.value || ''
				obj.FLot.number = v.FLot?.value || ''
				// 生产日期
				obj.FProduceDate.value = v.FProduceDate.value || '';
				// 有效期至
				obj.FExpiryDate.value = v.FExpiryDate.value || ''
				detailedList.value.push(obj)
			})
			// console.log(detailedList.value, 'detailedList');


		}
		calculateTotalByMaterialAndLot()
	})
	// 同物料同批号的数据合并，数量累计
	const calculateTotalByMaterialAndLot = () => {
		detailedList.value = detailedList.value.reduce((acc : any, curr : any) => {

			const index = acc.findIndex(
				(item : any) =>
					item.FMaterialId.number ===
					curr.FMaterialId.number &&
					item.FLot.number == curr.FLot.number &&
					item.FSrcStockId.number == curr.FSrcStockId.number &&
					item.FDestStockLocId.number == curr.FDestStockLocId.number &&
					item.FDestStockId.number == curr.FDestStockId.number &&
					item.FDestStockLocId.number == curr.FDestStockLocId.number
			);
			if (index !== -1) {
				acc[index].FBaseQty.value = Number(acc[index].FBaseQty.value) + Number(
					curr.FBaseQty.value
				);

			} else {
				acc.push({
					...curr,
				});
			}
			return acc;
		}, []);

	}
</script>

<style lang="less" scoped>
	.productionOrderDetails {
		padding: 28rpx;
		background: #f6f6f6;
		min-height: 100%;

		>view {
			padding: 28rpx;
			margin-bottom: 20rpx;
			border-radius: 20rpx;
			background-color: #fff;
		}

		.title {
			display: flex;
			align-items: center;
			font-size: 40rpx;
			padding-top: 0;
			margin-bottom: 0;
			background-color: #f6f6f6;
		}

		.orderData {
			.order_head {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 10rpx 0 20rpx;
				border-bottom: 1px solid #ccc;
				margin-bottom: 20rpx;

				.order_head_left {
					font-weight: 700;
					font-size: 36rpx;
				}
			}

			.orderDataItem {
				padding: 14rpx 0;
				justify-content: space-between;

				.key {
					font-size: 30rpx;
					white-space: nowrap;
					color: #666;
				}

				.value {
					box-sizing: border-box;
					font-size: 30rpx;
					flex: 1 0 0;
					margin: 0 0 0 20rpx;
					text-align: right;
					line-height: normal;
				}
			}
		}
	}

	.btns {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100vw;
		padding: 28rpx;
		display: flex;
		justify-content: flex-end;
		margin-top: 28rpx;
		z-index: 99;
		background-color: #fff;

		view {
			display: flex;
			align-items: center;
			justify-content: center;
			flex: 1;
			padding: 30rpx;
			margin-right: 20rpx;
			border-radius: 24rpx;
			font-size: 30rpx;
			background-color: #3974f6;
			color: #fff;
		}

		>view:last-child {
			margin-right: 0 !important;
		}

		.pay {
			border: 1px solid #3974f6;
			background-color: transparent;
			color: #3974f6;
		}
	}

	.purse {
		width: 100%;

		.p_item {
			padding: 20rpx 22rpx;
			margin-bottom: 16rpx;
			border-radius: 10rpx;
			background: #f6f6f6;

			font-size: 30rpx;

			.title {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 2rpx 0 24rpx;
				border-bottom: 1px solid #eeeeee;
				font-weight: 500;
				font-size: 34rpx;
				color: #000000;

				.status {
					color: #3974f6;
					font-size: 22rpx;
				}
			}

			.content {
				flex-wrap: wrap;
				padding-top: 20rpx;

				.c_item {
					width: 50%;
					margin-bottom: 26rpx;
					color: #111;
				}
			}

			.btn {
				display: flex;
				justify-content: flex-end;
				padding-top: 12rpx;

				view {
					padding: 12rpx 24rpx;
					border-radius: 10rpx;
					background: #3974f6;
					color: #fff;
				}
			}
		}
	}

	.actionSheetContent {
		padding: 20rpx;
		min-height: 50vh;
	}
</style>